﻿using ChatCommon;
using Lidgren.Network;
using NetBrick.Server;

namespace ChatServer
{
    public class ChatPeer : BasePeer
    {
        public ChatPeer(NetConnection connection) : base(connection)
        {
            Authenticated = false;
        }

        public override void OnConnect()
        {
            Log.Info("An unauthenticated user connected.");
        }

        public void Authenticate(string username)
        {
            Authenticated = true;
            Username = username;
            Log.Info("User {0} joined.", Username);
            var joinPacket = Program.ChatServer.CreatePacket(ChatPacketCode.PlayerJoin);
            joinPacket.Write(Username);
            Program.ChatServer.BroadcastPacket(joinPacket, NetDeliveryMethod.ReliableOrdered);
        }

        public override void OnDisconnect(string reason)
        {
            if (Authenticated)
            {
                Log.Info("User {0} left. Reason: {1}", Username, reason);
                var leavePacket = Program.ChatServer.CreatePacket(ChatPacketCode.PlayerLeave);
                leavePacket.Write(Username);
                Program.ChatServer.BroadcastPacket(leavePacket, NetDeliveryMethod.ReliableOrdered);
            }
            else
            {
                Log.Info("An unauthenticated user disconnected.");
            }
        }

        public bool Authenticated { get; private set; }
        public string Username { get; private set; }
    }
}